{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "xla_flags = os.environ.get(\"XLA_FLAGS\", \"\")\n",
    "xla_flags += \" --xla_gpu_triton_gemm_any=True\"\n",
    "os.environ[\"XLA_FLAGS\"] = xla_flags\n",
    "os.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"] = \"false\"\n",
    "os.environ[\"MUJOCO_GL\"] = \"egl\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "import json\n",
    "from datetime import datetime\n",
    "\n",
    "import jax\n",
    "import jax.numpy as jp\n",
    "import matplotlib.pyplot as plt\n",
    "import mediapy as media\n",
    "import mujoco\n",
    "import wandb\n",
    "from brax.training.agents.ppo import networks as ppo_networks\n",
    "from brax.training.agents.ppo import train as ppo\n",
    "from etils import epath\n",
    "from flax.training import orbax_utils\n",
    "from IPython.display import clear_output, display\n",
    "from orbax import checkpoint as ocp\n",
    "\n",
    "from mujoco_playground import manipulation, wrapper\n",
    "from mujoco_playground.config import manipulation_params\n",
    "\n",
    "# Enable persistent compilation cache.\n",
    "jax.config.update(\"jax_compilation_cache_dir\", \"/tmp/jax_cache\")\n",
    "jax.config.update(\"jax_persistent_cache_min_entry_size_bytes\", -1)\n",
    "jax.config.update(\"jax_persistent_cache_min_compile_time_secs\", 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "env_name = \"LeapCubeReorient\"\n",
    "env_cfg = manipulation.get_default_config(env_name)\n",
    "randomizer = manipulation.get_domain_randomizer(env_name)\n",
    "ppo_params = manipulation_params.brax_ppo_config(env_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "## First run.\n",
    "# ppo_params.num_timesteps = 200_000_000\n",
    "# ppo_params.num_evals = 20\n",
    "\n",
    "## Second run (add torque limits & frictionloss).\n",
    "# ppo_params.num_timesteps = 100_000_000\n",
    "# ppo_params.num_evals = 10\n",
    "# env_cfg.obs_noise.random_ori_injection_prob = 0.1\n",
    "# ppo_params.learning_rate = 1e-4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pprint import pprint\n",
    "\n",
    "pprint(ppo_params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup wandb logging.\n",
    "USE_WANDB = False\n",
    "\n",
    "if USE_WANDB:\n",
    "  wandb.init(project=\"mjxrl\", config=env_cfg)\n",
    "  wandb.config.update({\n",
    "      \"env_name\": env_name,\n",
    "  })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SUFFIX = None\n",
    "\n",
    "# FINETUNE_PATH = \"/home/kevin/mujoco_playground/mujoco_playground/experimental/learning/checkpoints/LeapCubeReorient-20250103-170903\"\n",
    "# FINETUNE_PATH = \"/home/kevin/mujoco_playground/mujoco_playground/experimental/learning/checkpoints/LeapCubeReorient-20250103-174028\"\n",
    "# FINETUNE_PATH = \"/home/kevin/mujoco_playground/mujoco_playground/experimental/learning/checkpoints/LeapCubeReorient-20250103-201052\"\n",
    "FINETUNE_PATH = None\n",
    "\n",
    "# Generate unique experiment name.\n",
    "now = datetime.now()\n",
    "timestamp = now.strftime(\"%Y%m%d-%H%M%S\")\n",
    "exp_name = f\"{env_name}-{timestamp}\"\n",
    "if SUFFIX is not None:\n",
    "  exp_name += f\"-{SUFFIX}\"\n",
    "print(f\"{exp_name}\")\n",
    "\n",
    "# Possibly restore from the latest checkpoint.\n",
    "if FINETUNE_PATH is not None:\n",
    "  FINETUNE_PATH = epath.Path(FINETUNE_PATH)\n",
    "  latest_ckpts = list(FINETUNE_PATH.glob(\"*\"))\n",
    "  latest_ckpts = [ckpt for ckpt in latest_ckpts if ckpt.is_dir()]\n",
    "  latest_ckpts.sort(key=lambda x: int(x.name))\n",
    "  latest_ckpt = latest_ckpts[-1]\n",
    "  restore_checkpoint_path = latest_ckpt\n",
    "  print(f\"Restoring from: {restore_checkpoint_path}\")\n",
    "else:\n",
    "  restore_checkpoint_path = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ckpt_path = epath.Path(\"checkpoints\").resolve() / exp_name\n",
    "ckpt_path.mkdir(parents=True, exist_ok=True)\n",
    "print(f\"{ckpt_path}\")\n",
    "\n",
    "with open(ckpt_path / \"config.json\", \"w\") as fp:\n",
    "  json.dump(env_cfg.to_dict(), fp, indent=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_data, y_data, y_dataerr = [], [], []\n",
    "s_data, s_dataerr = [], []\n",
    "times = [datetime.now()]\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
    "\n",
    "\n",
    "def progress(num_steps, metrics):\n",
    "  # Log to wandb.\n",
    "  if USE_WANDB:\n",
    "    wandb.log(metrics, step=num_steps)\n",
    "\n",
    "  # Plot.\n",
    "  clear_output(wait=True)\n",
    "\n",
    "  times.append(datetime.now())\n",
    "  x_data.append(num_steps)\n",
    "  y_data.append(metrics[\"eval/episode_reward\"])\n",
    "  y_dataerr.append(metrics[\"eval/episode_reward_std\"])\n",
    "  s_data.append(metrics[\"eval/episode_reward/success\"])\n",
    "  s_dataerr.append(metrics[\"eval/episode_reward/success_std\"])\n",
    "\n",
    "  # Plot reward vs steps.\n",
    "  axes[0].set_xlim([0, ppo_params.num_timesteps * 1.25])\n",
    "  axes[0].set_ylim([0, 1400.0])\n",
    "  axes[0].set_xlabel(\"# environment steps\")\n",
    "  axes[0].set_ylabel(\"reward per episode\")\n",
    "  axes[0].set_title(f\"y={y_data[-1]:.3f}\")\n",
    "  axes[0].errorbar(x_data, y_data, yerr=y_dataerr, color=\"blue\")\n",
    "\n",
    "  # Plot success vs steps.\n",
    "  axes[1].set_xlim([0, ppo_params.num_timesteps * 1.25])\n",
    "  axes[1].set_ylim([0, 20])\n",
    "  axes[1].set_xlabel(\"# environment steps\")\n",
    "  axes[1].set_ylabel(\"successes\")\n",
    "  axes[1].set_title(f\"y={s_data[-1]:.3f}\")\n",
    "  axes[1].errorbar(x_data, s_data, yerr=s_dataerr, color=\"red\")\n",
    "\n",
    "  display(plt.gcf())\n",
    "\n",
    "\n",
    "def policy_params_fn(current_step, make_policy, params):\n",
    "  del make_policy  # Unused.\n",
    "  orbax_checkpointer = ocp.PyTreeCheckpointer()\n",
    "  save_args = orbax_utils.save_args_from_target(params)\n",
    "  path = ckpt_path / f\"{current_step}\"\n",
    "  orbax_checkpointer.save(path, params, force=True, save_args=save_args)\n",
    "\n",
    "\n",
    "training_params = dict(ppo_params)\n",
    "del training_params[\"network_factory\"]\n",
    "\n",
    "train_fn = functools.partial(\n",
    "  ppo.train,\n",
    "  **training_params,\n",
    "  network_factory=functools.partial(\n",
    "      ppo_networks.make_ppo_networks,\n",
    "      **ppo_params.network_factory\n",
    "  ),\n",
    "  restore_checkpoint_path=restore_checkpoint_path,\n",
    "  progress_fn=progress,\n",
    "  wrap_env_fn=wrapper.wrap_for_brax_training,\n",
    "  policy_params_fn=policy_params_fn,\n",
    "  randomization_fn=randomizer,\n",
    ")\n",
    "\n",
    "env = manipulation.load(env_name, config=env_cfg)\n",
    "eval_env = manipulation.load(env_name, config=env_cfg)\n",
    "make_inference_fn, params, _ = train_fn(environment=env, eval_env=eval_env)\n",
    "if len(times) > 1:\n",
    "  print(f\"time to jit: {times[1] - times[0]}\")\n",
    "  print(f\"time to train: {times[-1] - times[1]}\")\n",
    "\n",
    "# Make a final plot of reward and success vs WALLCLOCK time.\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
    "axes[0].set_ylim([0, 1400.0])\n",
    "axes[0].set_xlabel(\"wallclock time (s)\")\n",
    "axes[0].set_ylabel(\"reward per episode\")\n",
    "axes[0].set_title(f\"y={y_data[-1]:.3f}\")\n",
    "axes[0].errorbar(\n",
    "    [(t - times[0]).total_seconds() for t in times[:-1]],\n",
    "    y_data,\n",
    "    yerr=y_dataerr,\n",
    "    color=\"blue\",\n",
    ")\n",
    "axes[1].set_ylim([0, 20])\n",
    "axes[1].set_xlabel(\"wallclock time (s)\")\n",
    "axes[1].set_ylabel(\"successes\")\n",
    "axes[1].set_title(f\"y={s_data[-1]:.3f}\")\n",
    "axes[1].errorbar(\n",
    "    [(t - times[0]).total_seconds() for t in times[:-1]],\n",
    "    s_data,\n",
    "    yerr=s_dataerr,\n",
    "    color=\"red\",\n",
    ")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "# Save normalizer and policy params to the checkpoint dir.\n",
    "normalizer_params, policy_params, value_params = params\n",
    "with open(ckpt_path / \"params.pkl\", \"wb\") as f:\n",
    "  data = {\n",
    "    \"normalizer_params\": normalizer_params,\n",
    "    \"policy_params\": policy_params,\n",
    "    \"value_params\": value_params,\n",
    "  }\n",
    "  pickle.dump(data, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "inference_fn = make_inference_fn(params, deterministic=True)\n",
    "jit_inference_fn = jax.jit(inference_fn)\n",
    "\n",
    "eval_env = manipulation.load(env_name, config=env_cfg)\n",
    "jit_reset = jax.jit(eval_env.reset)\n",
    "jit_step = jax.jit(eval_env.step)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = jax.random.PRNGKey(1234)\n",
    "rollout = [state := jit_reset(rng)]\n",
    "actions = []\n",
    "rewards = []\n",
    "cube_angvel = []\n",
    "cube_angacc = []\n",
    "torques = []\n",
    "for i in range(env_cfg.episode_length):\n",
    "  act_rng, rng = jax.random.split(rng)\n",
    "  ctrl, _ = jit_inference_fn(state.obs, act_rng)\n",
    "  state = jit_step(state, ctrl)\n",
    "  rollout.append(state)\n",
    "  rewards.append({k[7:]: v for k, v in state.metrics.items() if k.startswith(\"reward/\")})\n",
    "  actions.append({\n",
    "      \"policy_output\": ctrl,\n",
    "      \"motor_targets\": state.info[\"motor_targets\"],\n",
    "  })\n",
    "  torques.append(jp.linalg.norm(state.data.actuator_force))\n",
    "  cube_angvel.append(env.get_cube_angvel(state.data))\n",
    "  cube_angacc.append(env.get_cube_angacc(state.data))\n",
    "  if state.done:\n",
    "    print(\"Done detected, stopping rollout.\")\n",
    "    break\n",
    "print(rollout[-1].info[\"success_count\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "render_every = 1\n",
    "fps = 1.0 / eval_env.dt / render_every\n",
    "print(f\"fps: {fps}\")\n",
    "\n",
    "traj = rollout[::render_every]\n",
    "\n",
    "scene_option = mujoco.MjvOption()\n",
    "scene_option.geomgroup[2] = True\n",
    "scene_option.geomgroup[3] = False\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_TRANSPARENT] = False\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_PERTFORCE] = False\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = True\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTFORCE] = False\n",
    "\n",
    "eval_env.mj_model.stat.meansize = 0.02\n",
    "eval_env.mj_model.stat.extent = 0.25\n",
    "eval_env.mj_model.vis.global_.azimuth = 140\n",
    "eval_env.mj_model.vis.global_.elevation = -25\n",
    "frames = eval_env.render(\n",
    "    traj, height=480, width=640, scene_option=scene_option, camera=\"side\"\n",
    ")\n",
    "media.show_video(frames, fps=fps)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
